<template>
  <e-container class="create-client" style="padding: 24px 0" :loading="loading">
    <div class="steps">
      <step :current="currentStep" />
    </div>
    <a-divider />
    <div class="form-section">
      <keep-alive>
        <component :is="forms[currentStep]" ref="form" />
      </keep-alive>
    </div>
    <a-divider />
    <div class="buttons">
      <div class="cancel">
        <a-button @click="handleBackToList">Back To List</a-button>
      </div>
      <a-button :disabled="currentStep === 0" @click="currentStep--">Previous</a-button>
      <a-button type="primary" style="margin-left: 24px" :disabled="!saveButtonAvailable" @click="handleNext">
        {{ currentStep === 2 ? 'Save' : 'Next' }}
      </a-button>
    </div>
    <a-modal
      v-model:visible="showBuSelector"
      width="888px"
      title="Please select a BU manager"
      wrap-class-name="primary-modal"
      ok-text="Save"
      :destroyOnClose="true"
      @cancel="showBuSelector = false"
    >
      <a-select ref="select" v-model:value="bumId" style="width: 120px">
        <a-select-option v-for="bum in buManagers" :key="bum.id" :value="bum.id">{{ bum.displayName }}</a-select-option>
      </a-select>
      <template #footer>
        <a-button key="back" @click="showBuSelector = false">Cancel</a-button>
        <a-button
          key="submit"
          type="primary"
          :loading="loading"
          :disabled="!saveButtonAvailable"
          @click="handleConfirmBU"
        >
          Confirm
        </a-button>
      </template>
    </a-modal>
  </e-container>
</template>

<script setup>
import { ref, toRaw, nextTick, inject } from 'vue'
import { useRouter } from 'vue-router'
import EContainer from '@/components/EContainer.vue'
import Step from './components/Steps.vue'
import Form0 from './components/Form0.vue'
import Form1 from './components/Form1.vue'
import Form2 from './components/Form2.vue'
import {
  CONFIRM_BACK_TO_LIST,
  CHECK_FORM_INTEGRITY,
  CREATE_CLIENT_SUCCESS,
  PLEASE_SELECT_BUN,
  CLIENT_IS_REACHED_LIMIT
} from '@/constants/message.js'
import TargetClient from '@/api/targetClient.js'
const { Modal, message } = inject('Feedback')
const forms = [Form0, Form1, Form2]
const form = ref(null)
const loading = ref(false)
const saveButtonAvailable = ref(true)
const showBuSelector = ref(false)
const currentStep = ref(0)
const postData = { clientOrg: {}, clientContact: {}, clientContactTouch: {} }
const router = useRouter()
const emits = defineEmits(['updated'])
const buManagers = ref([])
const bumId = ref(undefined)
TargetClient.getMyBum().then(({ data }) => {
  buManagers.value = data
  bumId.value = Array.isArray(data) && data.length > 0 ? data[0].id : undefined
})
const handleNext = () => {
  form.value.formInstance
    .validate()
    .then(() => {
      if (currentStep.value === 0) {
        postData.clientOrg = toRaw(form.value.apiData)
        currentStep.value++
        return
      }
      if (currentStep.value === 1) {
        postData.clientContact = toRaw(form.value.apiData)
        currentStep.value++
        nextTick(() => {
          form.value.setContacts(postData.clientContact.ContactName)
        })
        return
      }
      if (currentStep.value === 2) {
        postData.clientContactTouch = toRaw(form.value.apiData)
        const save = () => {
          loading.value = true
          saveButtonAvailable.value = false
          TargetClient.isAllowCreate()
            .then(({ data }) => {
              if (data) {
                showBuSelector.value = true
              } else {
                message.warning(CLIENT_IS_REACHED_LIMIT)
              }
            })
            .finally(() => {
              loading.value = false
              saveButtonAvailable.value = true
            })
        }
        if (postData.clientOrg.Currency === 1 && postData.clientOrg.CountryID !== 92) {
          Modal.confirm({
            content: 'This is not a client in China, do you confirm to use RMB as the payment currency',
            onOk: () => {
              save()
            }
          })
        } else {
          save()
        }
      }
    })
    .catch(() => {
      message.error(CHECK_FORM_INTEGRITY)
    })
}
const handleConfirmBU = () => {
  if (!bumId.value) {
    message.error(PLEASE_SELECT_BUN)
  } else {
    postData.bumid = bumId.value
    loading.value = true
    saveButtonAvailable.value = false
    TargetClient.save(postData)
      .then(res => {
        message.success(CREATE_CLIENT_SUCCESS)
        emits('updated')
        setTimeout(() => {
          router.replace('/target-clients')
          window.open(router.resolve({ name: 'Client Detail', params: { id: res.data } }).href, '_BLANK')
        }, 2000)
      })
      .catch(() => {
        saveButtonAvailable.value = true
        loading.value = false
      })
      .finally(() => {
        loading.value = false
      })
  }
}
const handleBackToList = () => {
  Modal.confirm({
    content: CONFIRM_BACK_TO_LIST,
    okButtonProps: { danger: true },
    onOk: () => {
      router.push('/target-clients')
    }
  })
}
</script>

<style lang="less" scoped>
.create-client {
  .form-section {
    padding: 0 300px;
  }
  .buttons {
    padding: 0 300px;
    text-align: center;
    position: relative;
    .cancel {
      display: inline-block;
      position: absolute;
      left: 300px;
    }
  }
}
</style>
<route lang="yaml">
name: Create New Client
path: /target-clients/create
</route>
